package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j

public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    // 订单超时
    @Scheduled(cron = "0 * * * * ?")
    public void overtimeorder() {
        log.info("订单超时{}", LocalDateTime.now());
        //查询超时订单
        List<Orders> list = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,
                LocalDateTime.now().plusMinutes(-15));//订单超过15分钟，自动取消
        if (list != null && list.size() > 0) {
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }

    //每天凌晨1点，派送中变成已完成
    @Scheduled(cron = "0 0 1 * * ?")
   // @Scheduled(cron = "0 * * * * ?")
    public void cleanup() {
        log.info("清理过期订单{}", LocalDateTime.now());
        //清理过期订单
        List<Orders> list = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,
                LocalDateTime.now().plusMinutes(-60));//订单超过1分钟，自动完成
        if (list != null && list.size() > 0) {
            for (Orders orders : list) {
                log.info("清理过期订单{}", orders.getId());
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
